package controllers

import (
	"app/models"
	beego "github.com/beego/beego/v2/server/web"
)

type AppController struct {
	beego.Controller
}

type JsonMsg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *AppController) Add() {
	name := c.GetString("name")
	ly := c.GetString("ly")
	hangy := c.GetString("hangY")
	jiBie := c.GetString("jiBie")
	Guphone := c.GetString("guPhone")
	phone := c.GetString("phone")
	app := models.App{
		Name:    name,
		Ly:      ly,
		HangY:   hangy,
		JiBie:   jiBie,
		GuPhone: Guphone,
		Phone:   phone,
	}
	err := models.DB.Create(&app).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *AppController) List() {
	var app []models.App
	page, _ := c.GetInt("p", 1)
	PageSize, _ := c.GetInt("s", 3)
	var total int64
	query := models.DB.Model(&models.App{})
	err := query.Count(&total).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "总数查找失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err = query.Offset((page - 1) * PageSize).Limit(PageSize).Find(&app).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "分页失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		JsonData := make(map[string]interface{})
		JsonData["total"] = total
		JsonData["app"] = app
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "分页成功",
			Data: JsonData,
		}
		c.ServeJSON()
	}
}
